package org.dromara.answer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.answer.domain.AiExamQuestions;
import org.dromara.answer.domain.AiQuestions;
import org.dromara.answer.domain.vo.AiQuestionsVo;
import org.dromara.answer.service.IAiExamQuestionsService;
import org.dromara.answer.service.IAiQuestionsService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.answer.domain.bo.AiExamsBo;
import org.dromara.answer.domain.vo.AiExamsVo;
import org.dromara.answer.domain.AiExams;
import org.dromara.answer.mapper.AiExamsMapper;
import org.dromara.answer.service.IAiExamsService;

import java.util.*;

/**
 * 考试/测验Service业务层处理
 *
 * @author Lion Li
 * @date 2025-04-09
 */
@RequiredArgsConstructor
@Service
public class AiExamsServiceImpl extends ServiceImpl<AiExamsMapper, AiExams> implements IAiExamsService {

    private final AiExamsMapper baseMapper;
    private final IAiExamQuestionsService examQuestionsService;
    private final IAiQuestionsService questionsService;

    /**
     * 查询考试/测验
     *
     * @param examId 主键
     * @return 考试/测验
     */
    @Override
    public AiExamsVo queryById(Long examId){

        AiExamsVo aiExamsVo = baseMapper.selectVoById(examId);

        aiExamsVo.setQuestions(qeuryQuestionsByExamId(examId));

        return aiExamsVo;
    }

    /**
     * 分页查询考试/测验列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 考试/测验分页列表
     */
    @Override
    public TableDataInfo<AiExamsVo> queryPageList(AiExamsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AiExams> lqw = buildQueryWrapper(bo);
        Page<AiExamsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的考试/测验列表
     *
     * @param bo 查询条件
     * @return 考试/测验列表
     */
    @Override
    public List<AiExamsVo> queryList(AiExamsBo bo) {
        LambdaQueryWrapper<AiExams> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AiExams> buildQueryWrapper(AiExamsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AiExams> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), AiExams::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getDescription()), AiExams::getDescription, bo.getDescription());
        lqw.eq(bo.getStartTime() != null, AiExams::getStartTime, bo.getStartTime());
        lqw.eq(bo.getEndTime() != null, AiExams::getEndTime, bo.getEndTime());
        lqw.eq(bo.getDuration() != null, AiExams::getDuration, bo.getDuration());
        lqw.eq(bo.getTotalScore() != null, AiExams::getTotalScore, bo.getTotalScore());
        lqw.eq(bo.getPassScore() != null, AiExams::getPassScore, bo.getPassScore());
        lqw.eq(bo.getStatus() != null, AiExams::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增考试/测验
     *
     * @param bo 考试/测验
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(AiExamsBo bo) {
        AiExams add = MapstructUtils.convert(bo, AiExams.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setExamId(add.getExamId());
        }
        examQuestionsService.saveOrUpdateByBo(bo.getExamQuestions(), bo.getExamId());
        return flag;
    }

    /**
     * 修改考试/测验
     *
     * @param bo 考试/测验
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(AiExamsBo bo) {
        AiExams update = MapstructUtils.convert(bo, AiExams.class);
        validEntityBeforeSave(update);
        examQuestionsService.saveOrUpdateByBo(bo.getExamQuestions(), bo.getExamId());
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AiExams entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除考试/测验信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public Integer getTotalQuestionsById(Long examId) {
        return Integer.valueOf(String.valueOf(examQuestionsService
                .lambdaQuery()
                .eq(AiExamQuestions::getExamId, examId)
                .count()));
    }

    @Override
    public List<AiQuestionsVo> qeuryQuestionsByExamId(Long examId) {

        List<AiExamQuestions> list = examQuestionsService.lambdaQuery()
                .eq(AiExamQuestions::getExamId, examId)
                .list();

        if (list.size() == 0){
            return new ArrayList<>();
        }

        HashMap<Long, AiExamQuestions> map = new HashMap<>();
        list.forEach(item -> {
            map.put(item.getQuestionId(), item);
        });

        List<AiQuestionsVo> questions = questionsService
                .lambdaQuery()
                .in(AiQuestions::getQuestionId, list.stream()
                .map(AiExamQuestions::getQuestionId).toList())
                .list()
                .stream()
                .map(item -> {
                    AiQuestionsVo question = MapstructUtils.convert(item, AiQuestionsVo.class);

                    AiExamQuestions examQuestions = map.get(question.getQuestionId());

                    question.setQuestionOrder(examQuestions.getQuestionOrder());
                    question.setQuestionScore(examQuestions.getQuestionScore());
                    return question;
                })
                .toList();

        return questions;
    }
}
